package com.fusion.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class FileUtils {

	/**
	 * @Description: 网络资源转file,用完以后必须删除该临时文件
	 * @param fileUrl 资源地址
	 * @author: 赵兴炎
	 * @date: 2019年7月10日
	 * @return: 返回值
	 */
	public static File netWorkFileToLocalFile(String fileUrl) {
		String path = System.getProperty("user.dir");
		File upload = new File(path, "tmp");
		if (!upload.exists()) {
			upload.mkdirs();
		}
		String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
		FileOutputStream downloadFile = null;
		InputStream openStream = null;
		File savedFile = null;
		try {
			savedFile = new File(upload.getAbsolutePath() + fileName);
			URL url = new URL(fileUrl);
			java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
			openStream = connection.getInputStream();
			int index;
			byte[] bytes = new byte[1024];
			downloadFile = new FileOutputStream(savedFile);
			while ((index = openStream.read(bytes)) != -1) {
				downloadFile.write(bytes, 0, index);
				downloadFile.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (openStream != null) {
					openStream.close();
				}
				if (downloadFile != null) {
					downloadFile.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return savedFile;
	}

}
